package com.ukao.cashregister.dialog;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mcxtzhang.commonadapter.rv.OnItemClickListener;
import com.ukao.cashregister.R;
import com.ukao.cashregister.adapter.CouponsAdapter;
import com.ukao.cashregister.base.BaseDialogFragment;
import com.ukao.cashregister.bean.Coupons;
import com.ukao.cashregister.bean.PayInfoBean;
import com.ukao.cashregister.bean.StringBean;
import com.ukao.cashregister.consts.Constant;
import com.ukao.cashregister.consts.SaveParamets;
import com.ukao.cashregister.eventbus.PayEvent;
import com.ukao.cashregister.listener.MyOnItemClickListener;
import com.ukao.cashregister.retrofit.ApiCallback;
import com.ukao.cashregister.utils.CheckUtils;
import com.ukao.cashregister.utils.DensityUtils;
import com.ukao.cashregister.utils.SystemUIUtils;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.utils.Utils;
import com.ukao.cashregister.widget.StateImageView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import rx.Observable;

/**
 * Created by ukaodev on 2017/6/2.
 */

public class CouponsDialogFragment extends BaseDialogFragment {

    @BindView(R.id.title)
    TextView couponsTitle;
    @BindView(R.id.coupons_recycler)
    RecyclerView mRecycler;
    Unbinder unbinder;
    CouponsAdapter mAdapter;
    @BindView(R.id.layout)
    LinearLayout layout;
    @BindView(R.id.close_btn)
    StateImageView closeBtn;
    @BindView(R.id.no_data)
    TextView noData;
    private List<Coupons> lists;
    private boolean isPayEnter;
    private int mCount;
    private ViewGroup.LayoutParams mParams;

    private PayInfoBean mPayInfo;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            isPayEnter = getArguments().getBoolean("isPayEnter", false);
            lists = (ArrayList<Coupons>) getArguments().getSerializable(ARG_PARAM1);
            mPayInfo = (PayInfoBean) getArguments().getSerializable(ARG_PARAM2);
        }
        mCount = isPayEnter ? 3 : 2;

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_fragment_coupons, container, false);
        unbinder = ButterKnife.bind(this, view);

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getDialog() != null) {
            SystemUIUtils.setStickFullScreen(getDialog().getWindow());
        }
        initListener();
        initView();
    }

    private void initView() {
        if (mPayInfo!=null&&!CheckUtils.isEmpty(mPayInfo.getCpnRelId())) {
            for (Coupons list : lists) {
                if (list.getId().equals(mPayInfo.getCpnRelId())) {
                    list.setCheck(true);
                    list.setEnableUse(1);
                    break;
                }
            }

        }
        couponsTitle.setText("优惠券");
        mAdapter = new CouponsAdapter(getActivity(), lists);
        mAdapter.setisPayEnter(isPayEnter);
        mRecycler.setLayoutManager(new GridLayoutManager(getActivity(), mCount));
        mAdapter.setOnItemClickListener(mOnItemClickListener);
        mRecycler.setAdapter(mAdapter);
        if (CheckUtils.isEmpty(lists)) {
            noData.setVisibility(View.VISIBLE);
            mRecycler.setVisibility(View.GONE);
        } else {
            noData.setVisibility(View.GONE);
            mRecycler.setVisibility(View.VISIBLE);
        }

    }


    protected void initListener() {
        //是收款界面打开就设置这个大小
        if (isPayEnter) {
            mParams = layout.getLayoutParams();
            mParams.width = DensityUtils.dip2px(activity, 1240);
            mParams.height= DensityUtils.dip2px(activity, 880);
            layout.setLayoutParams(mParams);
        }
    }

    private OnItemClickListener mOnItemClickListener = new MyOnItemClickListener() {
        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object o, int i) {
            super.onItemClick(viewGroup, view, o, i);
            Coupons coupons = (Coupons) o;
            if (coupons.getEnableUse()&&isPayEnter) {
                couponInfo(coupons.isCheck(), coupons,i);
            }
        }
    };


    /**
     * @param isNoUsecoupon 是否取消优惠卷
     * @param mitem
     */
    public void couponInfo(boolean isNoUsecoupon, final Coupons mitem,final int pos) {

        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("accessToken", SaveParamets.getToken(Utils.getContext()));
        Observable observable = null;
        if (isNoUsecoupon) {
            mHashMap.put("orderId", mPayInfo.getOrderId());
            observable = apiStores().canCouponInfo(Constant.createParameter(mHashMap));
        } else {
            mHashMap.put("orderId", mPayInfo.getOrderId());
            mHashMap.put("relId", mitem.getId());/*订单优惠券id*/
            observable = apiStores().userCouponInfo(Constant.createParameter(mHashMap));
        }
        addSubscription(observable,
                new ApiCallback<StringBean>() {
                    @Override
                    public void onSuccess(StringBean model) {
                        if (model.getHttpCode() == 200) {
                            mitem.setCheck(!mitem.isCheck());
                            if (mitem.isCheck()){
                                mPayInfo.setCouponAmt(mitem.getAmount());
                                mPayInfo.setCpnRelId(mitem.getId());
                                mPayInfo.setCpnUseBalance(mitem.getUseBalance());
                                List<Coupons> mData = mAdapter.getDatas();
                                for (int j = 0; j < mData.size(); j++) {
                                    if (pos != j) {
                                        mData.get(j).setCheck(false);
                                    }
                                }
                            }else{
                                mPayInfo.setCouponAmt(0);
                                mPayInfo.setCpnRelId("");
                            }
                            mAdapter.notifyDataSetChanged();
                            PayEvent.postNoData(PayEvent.Message.coupon);

                        } else {
                            T.show(model.getMsg());
                        }

                    }


                    @Override
                    public void onFinish() {

                    }

                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick(R.id.close_btn)
    public void onViewClicked() {
        dismiss();
    }
}
